/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.amit.sendmail;

import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.SimpleEmail;

/**
 *
 * @author amit
 */
public class SendMail {

    final String hostName;
    final String port;
    final String userName;
    final String password;
    final String fromEmail;
    final String fromName;

    public SendMail(String hostName, String port, String userName, String password, String fromEmail, String fromName) {
        this.hostName = hostName;
        this.port = port;
        this.userName = userName;
        this.password = password;
        this.fromEmail = fromEmail;
        this.fromName = fromName;
    }

    public boolean sendPlainTextMessage(String toEmail, String toName, String subject, String message) {
        try {
            SimpleEmail email = new SimpleEmail();
            email.setHostName(hostName);
            email.setSslSmtpPort(port);
            email.setTLS(true);
            email.setAuthentication(userName, password);
            email.addTo(toEmail, toName);
            email.setFrom(fromEmail, fromName);
            email.setSubject(subject);
            email.setMsg(message);
            email.send();
            return true;
        } catch (EmailException ex) {
            Logger.getLogger(SendMail.class.getName()).log(Level.SEVERE, null, ex);
        }
        return false;
    }

    public void sendPlainTextMessageInNewThread(final String toEmail, final String toName, final String subject, final String message) {
           Thread t = new Thread(new Runnable() {

            public void run() {
                System.out.println("SENDING MESSAGE!");
                sendPlainTextMessage(toEmail, toName, subject, message);
                System.out.println("MESSAGE SENT");
            }
        });
        t.start();
    }
}
